import { validate, ValidationError } from 'class-validator';
import { plainToInstance } from 'class-transformer';
function extractErrors(errors:any, parentPath = '') {
    return errors.map((item:any) => {
        // 构建当前属性的完整路径
        const currentPath = parentPath ? `${parentPath}.${item.property}` : item.property;
        
        // 当前层的错误信息
        let currentError = '';
        if (item.constraints) {
            currentError = `${currentPath}: ${Object.values(item.constraints).join(';')}`;
        }
        
        // 递归处理子级的错误信息
        let childErrors = '';
        if (item.children && item.children.length > 0) {
            childErrors = extractErrors(item.children, currentPath);
        }
        
        // 合并当前错误和子级错误
        return [currentError, childErrors].filter(Boolean).join('<br/>');
    }).filter(Boolean).join('<br/>');
}





/**
 * 校验 DTO 的通用函数
 * @param dtoClass DTO 类
 * @param data 要校验的数据
 * @param skipMissingProperties 是否跳过缺失属性校验
 * @returns 校验错误数组
 */
export async function validateDto<T extends object>(
    dtoClass: new () => T,
    data: any,
    skipMissingProperties = false
): Promise<any> {
    const dtoInstance = plainToInstance(dtoClass, data);
    let errors = await validate(dtoInstance, {
        skipMissingProperties,
        whitelist: false,
        forbidNonWhitelisted: false
    });
    if (errors.length > 0) {
        const err = extractErrors(errors)
        return {
            code: 500,
            message: err,
        };
    }
    return false;
}



